package com.marvels.financial.loan.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.CommonProperties;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.financial.consum.FinancialConsumerApproveApi;
import com.marvels.financial.loan.dao.McfeLendingProcessDao;
import com.marvels.financial.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.financial.loan.dto.McfeLendingProcess;
import com.marvels.financial.loan.dto.PaymentResponse;
import com.marvels.financial.loan.service.ILoanApplyMqProduct;
import com.marvels.financial.loan.service.LoanAuditApi;
import com.marvels.financial.loan.service.LoanPaymentApi;
import com.marvels.financial.loan.service.TimePullWaitLendInfoApi;

@Service
public class TimePullWaitLendInfoImpl implements TimePullWaitLendInfoApi{
	
	@Autowired
	private LoanPaymentApi loanPaymentApi;

	@Autowired
	private LoanAuditApi loanAuditApi;

	@Autowired
	private McfeLendingProcessDao mcfeLendingProcessMapper;

	@Autowired
	private ILoanApplyMqProduct iLoanApplyMqProduct;
	
	@Autowired
	private FinancialConsumerApproveApi consumerApproveApi;
	
	
	public void pullWaitLendInfo(){
		
//		McsmSystemParam mcsmSystemParam=new McsmSystemParam();
//		mcsmSystemParam.setParamNames(new String[] { MarvelsConstant.AUTO_DF_FUNDS});
//		List<McsmSystemParam> params = consumSystemApi.paramList(mcsmSystemParam);
//		String[] fundCodes=null;
//		if(null!=params && params.size()>0){
//			String paramValue = params.get(0).getParamValue();
//			fundCodes = paramValue.split(",");
//		}else{
//			MarvelsLogUtil.getInstance().info(">>>>>>>>>>未配置自动放款资金源");
//		}
//		WaitLendInfoDTO infoDTO=new WaitLendInfoDTO();
//		infoDTO.setFundCodeList(Arrays.asList(fundCodes));
//		infoDTO.setProductTypeList(null);
//		infoDTO.setStatus("P05");
//		//调用审批服务拉取待放款数据
//		List<String> list=approveApi.selectWaitLendInfo(infoDTO);
//		if(list==null || list.size()<1){
//			MarvelsLogUtil.getInstance().info(">>>>>>>>>>无需要自动放款的信息");
//			return;
//		}
//		String loanIds="";
//		for(String loanId:list){
//			loanIds=loanId+","+loanIds;
//		}
//		//执行放款操作
//		approveApi.loanOperation(loanIds);
//		LoanAuditConditionDto conditionDto=new LoanAuditConditionDto();
//		conditionDto.setOperationStatus("1");
//		conditionDto.setLoanIds(loanIds.substring(0, loanIds.length()-1));
//		try {
//			//执行审批通过字段
//			loanAuditApi.executeApplyAudist(conditionDto);
//		} catch (MarvelsBusinessException e) {
//			MarvelsLogUtil.getInstance().error(">>>>>>>>自动放款审核通过失败");
//		}
//		
		MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>自动放款的放款定时处理任务开始");
		String onOff = CommonProperties.getTimingPayment();// 是否开启定时任务
		if (!"on".equalsIgnoreCase(onOff)) {
			MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>自动放款的放款定时处理任务未开启");
			return;
		}
		long threadId = Thread.currentThread().getId();
		MarvelsLogUtil.getInstance().info(">>>>>>>>>>线程号:" + threadId + "自动放款的放款定时任务处理开始");
		// 先锁住一批需要放款的数据
		String batName = threadId + UUID.randomUUID().toString().replace("-", "");
		int count = mcfeLendingProcessMapper.updateAuditBatName(batName, String.valueOf(threadId), "F7","2");// 支付中
		if (count < 1) {// 没有需要放款的数据
			MarvelsLogUtil.getInstance().info(">>>>>>>>>>线程号:" + threadId + "自动放款的放款定时任务处理线程没有需要放款的数据:");
			return;
		}
		// 查询出当前批次锁住的需要放款的数据
		List<McfeLendingProcess> list = mcfeLendingProcessMapper.selectByBatName(batName, String.valueOf(threadId),"F7");
		if (list != null && list.size() > 0) {
			for (McfeLendingProcess mcfeLendingProcess : list) {
				String loanId = mcfeLendingProcess.getLoanId();
				String auditMsg = "";
				String auditStatus = "";
				String applyStatus="";
				MarvelsLogUtil.getInstance().info(">>>>>>>>>>线程号:" + threadId + ",loanId" + loanId + "自动放款的放款任务开始");
				McamLoanApplyInfoDTO mcamLoanApplyInfo = new McamLoanApplyInfoDTO();
				mcamLoanApplyInfo.setLoanId(loanId);
				McamLoanApplyInfoDTO mcamLoanApplyInfoDTO = consumerApproveApi.selectLoanApplyInfo(mcamLoanApplyInfo);
				if (!"F03".equalsIgnoreCase(mcamLoanApplyInfoDTO.getStatus())) {// 先判断该笔放款在进件表中是否处于待放款状态
					MarvelsLogUtil.getInstance()
							.info(">>>>>>>>>>>>>>loanId" + loanId + ",自动放款的放款进件表状态:" + mcamLoanApplyInfoDTO.getStatus());
					continue;
				}
				// 判断限额
				try {
					if (loanAuditApi.judgeLoanLimit(mcfeLendingProcess.getAviAmount(),
							mcfeLendingProcess.getFundSource() + "")) {
						MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>>>loanId" + loanId + ",自动放款的放款资金源单日限额超限");
						continue;
					}
				} catch (MarvelsBusinessException e1) {
					MarvelsLogUtil.getInstance().error(">>>>>>>>>>>>>>loanId" + loanId + ",自动放款的放款任务判断限额失败:", e1);
				} catch (Exception e) {
					MarvelsLogUtil.getInstance().error(">>>>>>>>>>>>>>loanId" + loanId + ",自动放款的放款任务判断限额异常:", e);
				}

				PaymentResponse response = new PaymentResponse();
				try {
					response = loanPaymentApi.excuteLoanPayment(loanId,"F7");
				} catch (Exception e) {
					MarvelsLogUtil.getInstance().error(">>>>>>>loanId" + loanId + "自动放款的放款异常:", e);
				}
				if ("0".equals(response.getCode())) {
					auditStatus = "F2";
					auditMsg = "放款成功";
				} else {
					auditStatus = "F10";
					auditMsg = "处理中";
				}
				// 持久化审核信息
				McfeLendingProcess process = new McfeLendingProcess();
				process.setOrderNumber(response.getOrderNumber());
				process.setMsg(mcfeLendingProcess.getMsg()+"#"+response.getMsg());
				process.setStatus(auditStatus);
				process.setIsBusy("0");// 将审核表状态改为空闲
				process.setFundReturnTime(new Date());
				process.setUpdatedBy("system");
				process.setUpdatedDate(new Date());
				process.setOriginalStatus("F7");
				process.setLoanId(loanId);
				int countInsert = mcfeLendingProcessMapper.updateAuditResult(process);
				if (countInsert < 1) {
					MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>>>loanId" + loanId + ",自动放款的放款审核信息失败");
				}
				MarvelsLogUtil.getInstance().info(">>>>>>>>>>线程号:" + threadId + ",loanId" + loanId + "自动放款的放款定时任务结束");
			}
		}
		return;
	}
}
